package com.chaos.system.service.amap;

import com.alibaba.fastjson.JSONObject;
import com.chaos.system.api.dto.AmapAddressDto;
import com.chaos.system.api.dto.AmapGeoDto;
import com.chaos.system.service.third.AmapThirdFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * 高德地图
 *
 * @author Jacky Cui
 * @date 2020/2/15 15:52
 */
@Component
@Slf4j
public class AmapService {
    @Value("${amap.key:}")
    String key;

    @Autowired
    private AmapThirdFeign amapThirdFeign;

    public AmapGeoDto geo(String city, String address) {
        JSONObject resp = amapThirdFeign.geo(city, address, key);
        log.info(resp.toJSONString());
        String status = (String) resp.get("status");
        AmapGeoDto g = null;
        if (status.equals("1")) {
            ArrayList geocodes = (ArrayList) resp.get("geocodes");
            LinkedHashMap geocode = (LinkedHashMap) geocodes.get(0);
            String location = (String) geocode.get("location");
            String[] ls = location.split(",");
            g = AmapGeoDto.builder().longitude(ls[0]).latitude(ls[1]).build();
            g.setGeo(new GeoHashUtil().encode(Double.parseDouble(g.getLatitude()), Double.parseDouble(g.getLongitude())));
        }
        return g;
    }

    public AmapAddressDto regeo(String lng, String lat) {
        String location = lng + "," + lat;
        JSONObject resp = amapThirdFeign.regeo(location, key, 200, "all");
        LinkedHashMap map = (LinkedHashMap) resp.get("regeocode");
        LinkedHashMap am = (LinkedHashMap) map.get("addressComponent");
        AmapAddressDto amapAddressDto = new AmapAddressDto();

        Object city = am.get("city");
        amapAddressDto.setCity(city instanceof String ? (String) city : "");

        Object province = am.get("province");
        amapAddressDto.setProv(province instanceof String ? (String) province : "");

        Object district = am.get("district");
        amapAddressDto.setDist(district instanceof String ? (String) district : "");

        Object formatted_address = map.get("formatted_address");
        amapAddressDto.setAddr(formatted_address instanceof String ? (String) formatted_address : "");
        return amapAddressDto;
    }
}